package com.dhz.common.solr;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.ContentStream;
import org.springframework.util.Assert;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

/**
 * 查询参数处理
 *
 * @author Fyduan
 */
public class SolrRealtimeGetRequest extends SolrRequest<QueryResponse> {

    private static final long serialVersionUID = 1500782684874146272L;
    private Collection<String> ids;

    public SolrRealtimeGetRequest(Serializable... ids) {
        this(Arrays.asList(ids));
    }

    public SolrRealtimeGetRequest(Collection<? extends Serializable> ids) {
        super(METHOD.GET, "/get");

        Assert.notEmpty(ids, "At least one 'id' is required for real time get request.");
        Assert.noNullElements(ids.toArray(), "Real time get request can't be made for 'null' id.");

        toStringIds(ids);
    }

    /**
     * 转换 ID集合 {@link Collection} 的元素为String
     * @param ids {@link Collection}
     */
    private void toStringIds(Collection<? extends Serializable> ids) {

        this.ids = new ArrayList<String>(ids.size());
        for (Serializable id : ids) {
            this.ids.add(id.toString());
        }
    }

    @Override
    public SolrParams getParams() {
        return new ModifiableSolrParams().add("ids", this.ids.toArray(new String[this.ids.size()]));
    }

    @Override
    public Collection<ContentStream> getContentStreams() throws IOException {
        return null;
    }

    @Override
    protected QueryResponse createResponse(SolrClient client) {
        return new QueryResponse();
    }
}
